"""
AI Chat服务层
提供AI提供商连接测试、消息处理等业务逻辑
"""

import json
import time
import requests
import base64
from typing import Dict, Any, Optional
from django.conf import settings
from .models import AIProvider


class AIProviderTestService:
    """AI提供商连接测试服务"""
    
    def __init__(self, provider: AIProvider):
        self.provider = provider
        self.api_key = self._decrypt_api_key(provider.api_key)
        self.api_endpoint = provider.api_endpoint.rstrip('/')
        self.provider_type = provider.provider_type

    def _decrypt_api_key(self, encrypted_key: str) -> str:
        """简单的API密钥解密"""
        if not encrypted_key:
            return ""
        try:
            # 尝试Base64解码
            return base64.b64decode(encrypted_key.encode()).decode()
        except Exception:
            # 如果解码失败，返回原始字符串
            return encrypted_key
        
    def test_connection(self, test_message: str = "Hello, this is a test message.") -> Dict[str, Any]:
        """
        测试AI提供商连接 - 通过访问/models端点验证连接

        Args:
            test_message: 测试消息内容（保留参数兼容性）

        Returns:
            Dict包含测试结果
        """
        start_time = time.time()

        try:
            result = self._test_models_endpoint()
            response_time = round(time.time() - start_time, 3)

            return {
                'provider_id': self.provider.id,
                'provider_name': self.provider.name,
                'provider_type': self.provider_type,
                'status': 'success',
                'response_time': response_time,
                'message': '连接测试成功',
                'models_count': len(result.get('data', [])),
                'available_models': [model.get('id', 'unknown') for model in result.get('data', [])[:5]]  # 只显示前5个模型
            }

        except Exception as e:
            response_time = round(time.time() - start_time, 3)
            return {
                'provider_id': self.provider.id,
                'provider_name': self.provider.name,
                'provider_type': self.provider_type,
                'status': 'error',
                'response_time': response_time,
                'message': f'连接测试失败: {str(e)}',
                'error': str(e)
            }

    def _test_models_endpoint(self) -> Dict[str, Any]:
        """测试访问/models端点"""
        headers = {
            'Authorization': f'Bearer {self.api_key}',
            'Content-Type': 'application/json'
        }

        # 尝试访问/models端点
        models_url = f"{self.api_endpoint}/models"

        response = requests.get(
            models_url,
            headers=headers,
            timeout=10
        )

        if response.status_code != 200:
            raise Exception(f"API请求失败: HTTP {response.status_code} - {response.text[:200]}")

        try:
            result = response.json()
            return result
        except json.JSONDecodeError:
            raise Exception("API返回的不是有效的JSON格式")




# TODO: 后续可以添加其他服务类，如AIConversationService等
